package com.zhuyuan.controller;

import com.zhuyuan.Entity.Food;
import com.zhuyuan.common.R;
import com.zhuyuan.dto.FoodDto;
import com.zhuyuan.repository.FoodRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/food")
@Api(tags = "食物选择相关接口")
public class FoodController {
    private final FoodRepository foodRepository;

    public FoodController(FoodRepository foodRepository) {
        this.foodRepository = foodRepository;
    }

    @GetMapping("/foods")
    @ApiOperation("查询所有食物")
    public R<List<String>> fillAll(){
        List<Food> list = foodRepository.findAll();
        List<String> foods = new ArrayList<>();
        for (Food food : list) {
            foods.add(food.getFood());
        }
        return R.success(foods);
    }

    @PostMapping("/saveFoods")
    @ApiOperation("新增食物")
    public R<String> saveFoods(@RequestBody FoodDto foodDto){
        log.info("食物：{}",foodDto);
        List<String> foodList = foodDto.getFoods();
        List<Food> foods = new ArrayList<>();
        for (String foodName : foodList) {
            Food food = new Food();
            food.setFood(foodName);
            foods.add(food);
        }
        foodRepository.saveAll(foods);
        return R.success("新增成功");
    }

    @ApiOperation("删除食物")
    @DeleteMapping("/deleteFood")
    @Transactional
    public R<String> deleteFood(@RequestBody String food) {
        log.info("删除食物：{}",food);
        foodRepository.deleteFood(food);
        return R.success("删除成功");
    }
}
